package com.zcsy.commons.sms.dlife;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;


public class HttpUtils {
	
	private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
	
	public static String send(String url, boolean readAll, String enc) {
		BufferedReader br = null;
		StringBuilder sb;
		if(readAll) sb=new StringBuilder(1024);
		else sb=new StringBuilder(1024);
		sb.append("");
        HttpURLConnection urlconn=null;
        try {
        	urlconn = (HttpURLConnection) new URL(url).openConnection();
            urlconn.setConnectTimeout(60000);
            urlconn.setReadTimeout(60000);
            urlconn.connect();// 进行连接，但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
            br = new BufferedReader(new InputStreamReader(urlconn.getInputStream(),enc));//设置编码,否则中文乱码
            if(readAll){
                String lines;
                if((lines = br.readLine()) != null){
                	sb.append(lines.replace("encoding=\"UTF-8\"", "encoding=\"gbk\"")
                			.replace("encoding=\"utf-8\"", "encoding=\"gbk\"")
                			+"\n");
                }
                while ((lines = br.readLine()) != null){
                	sb.append(lines+"\n");
                }
            }else br.read();//读一个字节测试
        } catch (Exception e) {
            e.getStackTrace();
            log.error(url, e);
        } finally {
            try {br.close();} catch (Exception e) {}
            try {urlconn.disconnect();} catch (Exception e) {}
        }
        return sb.toString();
	}
	
	/**
	 * 返回的200编码不要变动，请求都是根据200判断请求成功与否
	 * @param url
	 * @param enc
	 * @param params
	 * @return
	 */
	public static Header httpClientPost(String url, String enc, Map<String, String> params) {
		try {
			HttpClient client = new HttpClient(); 
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
			//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
			client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
			
			client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);//指的是连接一个url的连接等待时间  60秒
		    client.getHttpConnectionManager().getParams().setSoTimeout(60000);//指的是连接上一个url，获取response的返回等待时间
			//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
			// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
//			HttpMethod method=new GetMethod(url);
			PostMethod postMethod = new PostMethod(url);
			postMethod.setRequestHeader("Connection", "close"); 
			if (params != null) {
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for (Entry<String, String> entry : params.entrySet()) {
					String key = entry.getKey();
					String value = entry.getValue();
					NameValuePair param = new NameValuePair( key , value );
					list.add(param);
				}
				NameValuePair[] arr = new NameValuePair[list.size()];
				postMethod.setRequestBody(list.toArray(arr));
			}
//			postMethod.addRequestHeader("Content-Type","text/xml");//
			//使用POST方法
			//HttpMethod method = new PostMethod("http://java.sun.com");
			int status = 0;
			try {
				status = client.executeMethod(postMethod);
				if (status == 200) {
	                Header header = new Header();
	                header.setState("200");
	                InputStream inputStream = postMethod.getResponseBodyAsStream();
	                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,enc));   
	                StringBuffer stringBuffer = new StringBuffer();   
	                String str= "";   
	                while((str = br.readLine()) != null){   
	                    stringBuffer.append(str );   
	                }   
	                header.setMsg(stringBuffer.toString());
//	                header.setMsg(postMethod.getResponseBodyAsString());
					return header;
				} else {
					Header header = new Header();
	                header.setState(String.valueOf(status));
	                header.setMsg("HTTP请求失败[status=" + postMethod.getStatusLine() + "]");
	                log.error("链接 " + url + " 异常,HTTP请求失败[status=" + postMethod.getStatusLine() + "]，参数:" + map2Str(params));
					return header;
				}
			} catch (Exception e) {
				Header header = new Header();
	            header.setState("REQUEST-FAIL");
	            header.setMsg("发起请求异常");
	            log.error("发起 " + url + " 请求异常，参数:" + map2Str(params), e);
				return header;
			} finally {
				postMethod.releaseConnection();
			}
		} catch (Exception e) {
			Header header = new Header();
            header.setState("REQUEST-FAIL");
            header.setMsg("发起请求异常");
            log.error("发起 " + url + " 请求异常，参数:" + map2Str(params), e);
			return header;
		}
	}
	
	/**
	 * 返回的200编码不要变动，请求都是根据200判断请求成功与否
	 * @param url
	 * @param enc
	 * @return
	 */
	public static Header httpClientGet(String url, String enc) {
		try {
			HttpClient client = new HttpClient(); 
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
			//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
			client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
			
			client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);//指的是连接一个url的连接等待时间  60秒
		    client.getHttpConnectionManager().getParams().setSoTimeout(60000);//指的是连接上一个url，获取response的返回等待时间
			//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
			// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
			HttpMethod method=new GetMethod(url);
			//使用POST方法
			//HttpMethod method = new PostMethod("http://java.sun.com");
			int status = 0;
			try {
				status = client.executeMethod(method);
				if (status == 200) {
	                Header header = new Header();
	                header.setState("200");
	                InputStream inputStream = method.getResponseBodyAsStream();
	                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,enc));   
	                StringBuffer stringBuffer = new StringBuffer();   
	                String str= "";   
	                while((str = br.readLine()) != null){   
	                    stringBuffer.append(str );   
	                }   
	                header.setMsg(stringBuffer.toString());
//	                header.setMsg(method.getResponseBodyAsString());
					return header;
				} else {
					Header header = new Header();
	                header.setState(String.valueOf(status));
	                header.setMsg("HTTP请求失败[status=" + method.getStatusLine() + "]");
	                log.error("链接 " + url + " 异常,HTTP请求失败[status=" + method.getStatusLine() + "]");
	                return header;
				}
			} catch (Exception e) {
				Header header = new Header();
	            header.setState("REQUEST-FAIL");
	            header.setMsg("发起请求异常");
	            log.error("发起 " + url + " 请求异常", e);
				return header;
			} finally {
				method.releaseConnection();
			}
		} catch (Exception e) {
			Header header = new Header();
            header.setState("REQUEST-FAIL");
            header.setMsg("发起请求异常");
            log.error("发起 " + url + " 请求异常", e);
			return header;
		}
		
	}
	
	/**
	 * 返回的200编码不要变动，请求都是根据200判断请求成功与否
	 * @param url
	 * @param enc
	 * @param timeout 超时时间 单位秒
	 * @return
	 */
	public static Header httpClientPost(String url, String enc, Map<String, String> params, int timeout) {
		try {
			HttpClient client = new HttpClient(); 
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
			//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
			client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
			
			client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout*1000);//指的是连接一个url的连接等待时间  60秒
		    client.getHttpConnectionManager().getParams().setSoTimeout(timeout*1000);//指的是连接上一个url，获取response的返回等待时间
			//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
			// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
//			HttpMethod method=new GetMethod(url);
			PostMethod postMethod = new PostMethod(url);
			if (params != null) {
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for (Entry<String, String> entry : params.entrySet()) {
					String key = entry.getKey();
					String value = entry.getValue();
					NameValuePair param = new NameValuePair( key , value );
					list.add(param);
				}
				NameValuePair[] arr = new NameValuePair[list.size()];
				postMethod.setRequestBody(list.toArray(arr));
			}
//			postMethod.addRequestHeader("Content-Type","text/xml");//
			//使用POST方法
			//HttpMethod method = new PostMethod("http://java.sun.com");
			int status = 0;
			try {
				status = client.executeMethod(postMethod);
				if (status == 200) {
	                Header header = new Header();
	                header.setState("200");
	                InputStream inputStream = postMethod.getResponseBodyAsStream();
	                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,enc));   
	                StringBuffer stringBuffer = new StringBuffer();   
	                String str= "";   
	                while((str = br.readLine()) != null){   
	                    stringBuffer.append(str );   
	                }   
	                header.setMsg(stringBuffer.toString());
//	                header.setMsg(postMethod.getResponseBodyAsString());
					return header;
				} else {
					Header header = new Header();
	                header.setState(String.valueOf(status));
	                header.setMsg("HTTP请求失败[status=" + postMethod.getStatusLine() + "]");
	                log.error("链接 " + url + " 异常,HTTP请求失败[status=" + postMethod.getStatusLine() + "]，参数:" + map2Str(params));
					return header;
				}
			} catch (Exception e) {
				Header header = new Header();
	            header.setState("REQUEST-FAIL");
	            header.setMsg("发起请求异常");
	            log.error("发起 " + url + " 请求异常，参数:" + map2Str(params), e);
				return header;
			} finally {
				postMethod.releaseConnection();
			}
		} catch (Exception e) {
			Header header = new Header();
            header.setState("REQUEST-FAIL");
            header.setMsg("发起请求异常");
            log.error("发起 " + url + " 请求异常，参数:" + map2Str(params), e);
			return header;
		}
	}
	
	/**
	 * 返回的200编码不要变动，请求都是根据200判断请求成功与否
	 * @param url
	 * @param enc
	 * @param timeout 超时时间 单位秒
	 * @return
	 */
	public static Header httpClientGet(String url, String enc, int timeout) {
		try {
			HttpClient client = new HttpClient(); 
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
			//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
			client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
			
			client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout*1000);//指的是连接一个url的连接等待时间  60秒
		    client.getHttpConnectionManager().getParams().setSoTimeout(timeout*1000);//指的是连接上一个url，获取response的返回等待时间
			//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
			// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
			HttpMethod method=new GetMethod(url);
			//使用POST方法
			//HttpMethod method = new PostMethod("http://java.sun.com");
			int status = 0;
			try {
				status = client.executeMethod(method);
				if (status == 200) {
	                Header header = new Header();
	                header.setState("200");
	                InputStream inputStream = method.getResponseBodyAsStream();
	                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,enc));   
	                StringBuffer stringBuffer = new StringBuffer();   
	                String str= "";   
	                while((str = br.readLine()) != null){   
	                    stringBuffer.append(str );   
	                }   
	                header.setMsg(stringBuffer.toString());
//	                header.setMsg(method.getResponseBodyAsString());
					return header;
				} else {
					Header header = new Header();
	                header.setState(String.valueOf(status));
	                header.setMsg("HTTP请求失败[status=" + method.getStatusLine() + "]");
	                log.error("链接 " + url + " 异常,HTTP请求失败[status=" + method.getStatusLine() + "]");
	                return header;
				}
			} catch (Exception e) {
				Header header = new Header();
	            header.setState("REQUEST-FAIL");
	            header.setMsg("发起请求异常");
	            log.error("发起 " + url + " 请求异常", e);
				return header;
			} finally {
				method.releaseConnection();
			}
		} catch (Exception e) {
			Header header = new Header();
            header.setState("REQUEST-FAIL");
            header.setMsg("发起请求异常");
            log.error("发起 " + url + " 请求异常", e);
			return header;
		}
	}
	
	/**
	 * 返回的200编码不要变动，请求都是根据200判断请求成功与否
	 * @param url
	 * @param enc
	 * @param timeout 超时时间 单位秒
	 * @return
	 */
	public static Header httpClientGet(String url,  int timeout) {
		try {
			HttpClient client = new HttpClient(); 
//			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
			//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
			client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
			
			client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout*1000);//指的是连接一个url的连接等待时间  60秒
		    client.getHttpConnectionManager().getParams().setSoTimeout(timeout*1000);//指的是连接上一个url，获取response的返回等待时间
			//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
			// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
			HttpMethod method=new GetMethod(url);
			//使用POST方法
			//HttpMethod method = new PostMethod("http://java.sun.com");
			int status = 0;
			try {
				status = client.executeMethod(method);
				if (status == 200) {
	                Header header = new Header();
	                header.setState("200");
	                header.setMsg(method.getResponseBodyAsString());
//	                header.setMsg(method.getResponseBodyAsString());
					return header;
				} else {
					Header header = new Header();
	                header.setState(String.valueOf(status));
	                header.setMsg("HTTP请求失败[status=" + method.getStatusLine() + "]");
	                log.error("链接 " + url + " 异常,HTTP请求失败[status=" + method.getStatusLine() + "]");
	                return header;
				}
			} catch (Exception e) {
				Header header = new Header();
	            header.setState("REQUEST-FAIL");
	            header.setMsg("发起请求异常");
	            log.error("发起 " + url + " 请求异常", e);
				return header;
			} finally {
				method.releaseConnection();
			}
		} catch (Exception e) {
			Header header = new Header();
            header.setState("REQUEST-FAIL");
            header.setMsg("发起请求异常");
            log.error("发起 " + url + " 请求异常", e);
			return header;
		}
		
	}
	
	public static String httpClientPostSend(String url, String enc) {
		HttpClient client = new HttpClient(); 
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
		//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
		
		client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);//指的是连接一个url的连接等待时间  60秒
	    client.getHttpConnectionManager().getParams().setSoTimeout(60000);//指的是连接上一个url，获取response的返回等待时间
		//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
		// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
//		HttpMethod method=new GetMethod(url);
		PostMethod postMethod = new PostMethod(url);
//		postMethod.addRequestHeader("Content-Type","text/xml");//
		//使用POST方法
		//HttpMethod method = new PostMethod("http://java.sun.com");
		int status = 0;
		try {
			status = client.executeMethod(postMethod);
			if (status == 200) {
//				String response =new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));
//				response = URLDecoder.decode(response, "gb2312");
				InputStream inputStream = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,enc));   
                StringBuffer stringBuffer = new StringBuffer();   
                String str= "";   
                while((str = br.readLine()) != null){   
                    stringBuffer.append(str );   
                }   
				return stringBuffer.toString();
//				return postMethod.getResponseBodyAsString();
			} else {
				log.error("请求URL:" +url + ",状态=" + postMethod.getStatusLine());
				return "HTTP请求失败[status=" + postMethod.getStatusLine() + "]";
			}
		} catch (Exception e) {
			log.error("请求URL:" +url, e);
			return "HTTP请求失败";
		} finally {
			postMethod.releaseConnection();
		}
	}
	
	public static String httpClientPostSend(String url, String enc, Map<String, String> params) {
		HttpClient client = new HttpClient(); 
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
		
		//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
		
		client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);//指的是连接一个url的连接等待时间  60秒
	    client.getHttpConnectionManager().getParams().setSoTimeout(60000);//指的是连接上一个url，获取response的返回等待时间
		//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
		// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
//		HttpMethod method=new GetMethod(url);
		PostMethod postMethod = new PostMethod(url);
		postMethod.setRequestHeader("Content-Type","text/html; charset=utf-8");  
		if (params != null) {
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			for (Entry<String, String> entry : params.entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue();
				NameValuePair param = new NameValuePair( key , value );
				list.add(param);
			}
			NameValuePair[] arr = new NameValuePair[list.size()];
			postMethod.setRequestBody(list.toArray(arr));
		}
		
		//使用POST方法
		//HttpMethod method = new PostMethod("http://java.sun.com");
		int status = 0;
		try {
			status = client.executeMethod(postMethod);
			if (status == 200) {
//				String response =new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));
//				response = URLDecoder.decode(response, "gb2312");
				InputStream inputStream = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,enc));   
                StringBuffer stringBuffer = new StringBuffer();   
                String str= "";   
                while((str = br.readLine()) != null){   
                    stringBuffer.append(str );   
                }   
				return stringBuffer.toString();
//				return postMethod.getResponseBodyAsString();
			} else {
				log.error("请求URL:" +url + ",状态=" + postMethod.getStatusLine());
				return "HTTP请求失败[status=" + postMethod.getStatusLine() + "]";
			}
		} catch (Exception e) {
			log.error("请求URL:" +url, e);
			return "HTTP请求失败";
		} finally {
			postMethod.releaseConnection();
		}
	}
	
	public static String httpClientSend(String url, String enc) {
		HttpClient client = new HttpClient(); 
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, enc);
		//每个默认的HttpClient都会自动尝试从不是致命的错误中恢复，当一个建档IOException抛出时，HttpClient重复3次直到将Requset的全部内容发送到目标服务器。你可以通过以下代码来设置恢复机制。
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0,false));
		
		client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);//指的是连接一个url的连接等待时间  60秒
	    client.getHttpConnectionManager().getParams().setSoTimeout(60000);//指的是连接上一个url，获取response的返回等待时间
		//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);??
		// 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https 
		HttpMethod method=new GetMethod(url);
		//使用POST方法
		//HttpMethod method = new PostMethod("http://java.sun.com");
		int status = 0;
		try {
			status = client.executeMethod(method);
			if (status == 200) {
//				String response =new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));
//				response = URLDecoder.decode(response, "gb2312");
				InputStream inputStream = method.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,enc));   
                StringBuffer stringBuffer = new StringBuffer();   
                String str= "";   
                while((str = br.readLine()) != null){   
                    stringBuffer.append(str );   
                }   
				return stringBuffer.toString();
//				return method.getResponseBodyAsString();
			} else {
				log.error("请求URL:" +url + ",状态=" + method.getStatusLine());
				return "HTTP请求失败[status=" + method.getStatusLine() + "]";
			}
		} catch (Exception e) {
			log.error("请求URL:" +url, e);
			return "HTTP请求失败";
		} finally {
			method.releaseConnection();
		}
	}
	
	public static String httpSend(String url, boolean readAll, String enc) {
		BufferedReader br = null;
		StringBuilder sb;
		if(readAll) sb=new StringBuilder(1024);
		else sb=new StringBuilder(1024);
		sb.append("");
        HttpURLConnection urlconn=null;
        try {
        	urlconn = (HttpURLConnection) new URL(url).openConnection();
//        	urlconn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            urlconn.setConnectTimeout(60000);
            urlconn.setReadTimeout(60000);
            urlconn.connect();// 进行连接，但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
            br = new BufferedReader(new InputStreamReader(urlconn.getInputStream(),enc));//设置编码,否则中文乱码
            if(readAll){
                String lines;
                if((lines = br.readLine()) != null){
                	sb.append(lines.replace("encoding=\"UTF-8\"", "encoding=\"" + enc + "\"")
                			.replace("encoding=\"utf-8\"", "encoding=\"" + enc + "\"")
                			+"\n");
                }
                while ((lines = br.readLine()) != null){
                	sb.append(lines+"\n");
                }
            }else br.read();//读一个字节测试
        } catch (Exception e) {
            e.getStackTrace();
            log.error("请求异常:" + url, e);
        } finally {
            try {br.close();} catch (Exception e) {}
            try {urlconn.disconnect();} catch (Exception e) {}
        }
        return sb.toString();
	}
	
	public static String send(String url, boolean readAll) {
		return send(url, readAll, "utf-8");
	}
	
	public static String url2Encode(String url, String enc){
		try {
			return java.net.URLEncoder.encode(url, enc);
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
	
	public static String url2Decode(String url, String enc){
		try {
			return java.net.URLDecoder.decode(url, enc);
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
	
	public static HashMap<String, String> url2MapDecoder(String url, String enc) {
		HashMap<String, String> map=new HashMap<String, String>();
		for(String s: url.split("`")){
			try {
				int idx=s.indexOf("=");
				if(idx>0){
					map.put(s.substring(0,idx), java.net.URLDecoder.decode(s.substring(idx+1), enc));
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
				
		}
		return map;
	}
	
	public static HashMap<String, String> url2Map(String url) {
		HashMap<String, String> map=new HashMap<String, String>();
		for(String s: url.split("`")){
			int idx=s.indexOf("=");
			if(idx>0){
				map.put(s.substring(0,idx), s.substring(idx+1));
			}
		}
		return map;
	}
	
	public static String httpGet(String url) {
        HttpClient httpClient = new HttpClient();
        HttpMethod method = new GetMethod(url);
        try {
            int status = httpClient.executeMethod(method);
            if (status == HttpStatus.SC_OK) {
                return method.getResponseBodyAsString();
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            method.releaseConnection();
        }
    }
    
    public static String httpGetXml(String url) {
        String xml=httpGet(url);
        if(xml==null || !xml.startsWith("<?xml")) return null;
        return xml;
    }
    
    public static String getHttpUrlParam(String url,String paramName){
    	String beginStr=paramName+"=";
    	String endStr="&";
    	int beginIndex=url.indexOf(beginStr)+beginStr.length();
		int endIndex=url.indexOf(endStr,beginIndex);
		if(endIndex<0){
			endIndex=url.length();
		}
		if(beginIndex<0 || endIndex<beginIndex){
			return "";
		}
		return url.substring(beginIndex, endIndex);
    }
    
    public static String getHttpUrlParam(String url,String paramName, String split){
    	String beginStr=paramName+"=";
    	String endStr=split;
    	int beginIndex=url.indexOf(beginStr)+beginStr.length();
		int endIndex=url.indexOf(endStr,beginIndex);
		if(endIndex<0){
			endIndex=url.length();
		}
		if(beginIndex<0 || endIndex<beginIndex){
			return "";
		}
		return url.substring(beginIndex, endIndex);
    }
    
    /**
     * 转换编码 ISO-885Array-1到GB2312
     * @param str
     * @return
     */
	public static String convertEnc(String str, String sourceEnc, String targetEnc) {
		String result = "";
		try {
			result = new String(str.getBytes(sourceEnc), targetEnc);
//			result = new String(str.getBytes("ISO-885Array-1"), "GB2312");
		} catch (UnsupportedEncodingException ex) {
			result = ex.toString();
		}
		return result;
	} 
	
	/**
	 * MD5 加密
	 */
	public static String getMD5Str(String str, String enc) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes(enc));//"gb2312"
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString();
	}
	
	/**
	 * SHA1加密
	 * @param str
	 * @param enc
	 * @return
	 */
	public static String getSHA1(String str, String enc) {
		MessageDigest messageDigest = null;
		if (str == null) {
			return null;
		}
		try {
			messageDigest = MessageDigest.getInstance("SHA1");
			messageDigest.update(str.getBytes(enc));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer sha1StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				sha1StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			else
				sha1StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return sha1StrBuff.toString();

	}
	
	public static final Map<String, String> getRequestParamsInFilter(HttpServletRequest request) {
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				String vStr = "";
				try {
					if (request.getMethod().equals("POST")) {
						vStr = values[i];
					} else {
						vStr = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
						values[i] = vStr;
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				valueStr = (i == values.length - 1) ? valueStr +  vStr
						: valueStr + values[i] + ",";
			}
			
			params.put(name, valueStr);
		}
		return params;
	}
	
	public static final Map<String, String> getRequestParams(HttpServletRequest request) {
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				String vStr = "";
			    vStr = values[i];
				valueStr = (i == values.length - 1) ? valueStr +  vStr
						: valueStr + values[i] + ",";
			}
			
			params.put(name, valueStr);
		}
		return params;
	}
	
	public static boolean isChinese(char c) {  
	    Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);  
	    if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS  
	        || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS  
	        || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A  
	        || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION  
	        || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION  
	        || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {  
	      return true;  
	    }  
	    return false;  
	}  
	
	public static boolean isMessyCode(String strName) {  
	    Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");  
	    Matcher m = p.matcher(strName);  
	    String after = m.replaceAll("");  
	    String temp = after.replaceAll("\\p{P}", "");  
	    char[] ch = temp.trim().toCharArray();  
	    float chLength = ch.length;  
	    float count = 0;  
	    for (int i = 0; i < ch.length; i++) {  
	      char c = ch[i];  
	      if (!Character.isLetterOrDigit(c)) {  
	  
	        if (!isChinese(c)) {  
	          count = count + 1;  
	          System.out.print(c);  
	        }  
	      }  
	    }  
	    float result = count / chLength;  
	    if (result > 0.4) {  
	      return true;  
	    } else {  
	      return false;  
	    }  
	  
	  } 
	
	/**
	  * 判断是否为乱码
	  * 
	  * @param str
	  * @return
	  */
	 public static boolean isMessyCode2(String str) {
	  for (int i = 0; i < str.length(); i++) {
	   char c = str.charAt(i);
	   // 当从Unicode编码向某个字符集转换时，如果在该字符集中没有对应的编码，则得到0x3f（即问号字符?）
	   //从其他字符集向Unicode编码转换时，如果这个二进制数在该字符集中没有标识任何的字符，则得到的结果是0xfffd
	   //System.out.println("--- " + (int) c);
	   if ((int) c == 0xfffd) {
	    // 存在乱码
	    //System.out.println("存在乱码 " + (int) c);
	    return true;
	   }
	  }
	  return false; 
	 }
	
	public static String map2Str(Map<String, String> params) {
		StringBuffer url = new StringBuffer();
		int i = 0;
		for (Entry<String, String> entry : params.entrySet()) {
			String paramName = entry.getKey();
			String paramValue = entry.getValue();
			if (i == 0) {
				url.append("?");
			} else {
				url.append("&");
			}
			url.append(paramName).append("=").append(paramValue);
			i++;
		}
		return url.toString();
	}
	
	public static String appendUrl(String url, String paramterName, String paramterValue) {
		if (!StringUtils.isEmpty(paramterValue)) {
			int x = -1;
			int y = -1;
			if ((x = url.indexOf("&" + paramterName + "=")) < 0 && (y = url.indexOf("?" + paramterName + "=")) < 0) {
				if (url.lastIndexOf("?") >= 0) {
					url+="&";
				} else {
					url+="?";
				}
				url+=paramterName+"="+paramterValue;
			} else {
				int z = (x>y?x:y);
				int end = (url.indexOf("&",z+1) > 0 ? url.indexOf("&",z+1) : url.length());
				url = url.replace(url.substring(z+paramterName.length()+"&=".length(),end),paramterValue);
			}
		}	
		return url;
	}
	
	public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(ip.contains(":")){
            ip="invalid";
            log.error("无效的IP:"+ip);
        }
        return ip;
    }
	
	public static void main(String [] args) throws UnsupportedEncodingException {
//         String url = "http://dss/ss?userName=abc";
//         String userName = getHttpUrlParam(url,"userName","&");
//         System.out.println(userName);
		
//		String json = "{colHeader:[{display:\"操作\",name:\"orderId\",width:\"100px\",isHidden:false,operateURL:\"<a href=\'http://-----/xx.do?userId=${userId}\'>查看</a>|<a href=\'http://-----/xx.do?userId=${userId}\'>修改</a>\"}]}";
//		ColHeader headers = StringUtils.jsonStr2JavaObj(json, ColHeader.class);
//		System.out.println(8&(4|8|16|32|64));
//		System.out.println(2|4);//有2和4的权限，算出权限值6
//		System.out.println(4&6);//检验权限值中是否有4权限，如果返回>0则有权限
		
//		String s = "tangchizanzanzanä¸­";
//		boolean b = isMessyCode2(s);
//		System.out.println(b);
	}

	public static String getSignMessage(String url){
	    if(StringUtils.isEmpty(url))
	    	return url;
		int index = url.indexOf('?');
		if(index < 0)
			return url;
	    Map<String, String> params = new HashMap<String, String>();
		while(index > -1){
			int nxtStart = url.indexOf("&", index+1);
			int endIndex = nxtStart;
			if(nxtStart < 0)
				endIndex = url.length();
			
			if(endIndex > -1 && index<endIndex){
				String pairStr = url.substring(index+1, endIndex);
				int i = pairStr.indexOf('=');
				if(i>-1){
					String v = pairStr.substring(i+1);
					try {
						v = URLDecoder.decode(v, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					params.put(pairStr.substring(0,i), v);
				}
			} else
				break;
			index = nxtStart;
		}
		return getSignMessage(params);
	}
	public static String getSignMessage(Map<String, String> params) {
        StringBuilder signVal = new StringBuilder();
        Set<String> set = params.keySet();
        String[] keys = new String[set.size()];
        set.toArray(keys);
        Arrays.sort(keys, new MyComparator());
        for (String key : keys) {
            if ("sign".equals(key))  continue;
            String value = params.get(key);
            signVal.append(key).append(value);
        }
        return signVal.toString();
    }
	
	public static class MyComparator implements Comparator{
		private Collator collator = Collator.getInstance();// 点击查看中文api详解
		
		public int compare(Object o1, Object o2) {

			// 把字符串转换为一系列比特，它们可以以比特形式与 CollationKeys 相比较
			CollationKey key1 = collator.getCollationKey(o1.toString());// 要想不区分大小写进行比较用o1.toString().toLowerCase()
			CollationKey key2 = collator.getCollationKey(o2.toString());

			return key1.compareTo(key2);// 返回的分别为1,0,-1 分别代表大于，等于，小于。要想按照字母降序排序的话
										// 加个“-”号
		}
	}
}
